package com.wuyixu.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wuyixu.common.MsgData;
import com.wuyixu.domain.Cart;
import com.wuyixu.domain.User;
import com.wuyixu.service.CartService;
import com.wuyixu.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
	@Reference
	private UserService userService;
	@Reference
	private CartService cartService;
	@RequestMapping("toLogin")
	public String toLogin(Model model){
		return "user/login";
	}
	@RequestMapping("login")
	public String login(Model model,User user,HttpSession session){
		User u = userService.login(user);
		if(u==null)
			return "user/login";
		session.setAttribute("name",u);
		return "list";
	}
	@RequestMapping("toRegist")
	public String toRegist(Model model){
		
		return "user/regist";
	}
	@RequestMapping("checkExist")
	@ResponseBody
	public boolean checkExist(String username){
		return null==userService.getUserByName(username);
	}
	
	@RequestMapping("regist")
	public String regist(Model model,User user){
		User u = userService.regist(user);
		if(u!=null)
			return "redirect:toLogin";
		return "user/login";
	}
	@RequestMapping("addcart")
	@ResponseBody
	public MsgData addCart(HttpSession session, Model model,Cart cart){
		User loginUser=(User)session.getAttribute("name");
		if(loginUser==null){
			return new MsgData(1,"对不起,您尚未登录");
		}
		cart.setUid(loginUser.getUid());
		int result = cartService.add(cart);
		return result>0?new MsgData("保存成功"):new MsgData(2,"加入失败,请稍后再试");
	}
	@RequestMapping("cartlist")
	public String cartlist(Model model,HttpSession session){
		User loginUser=(User)session.getAttribute("name");
		List<Cart> list = cartService.list(loginUser.getUid());
		model.addAttribute("cartList", list);
		return "user/cartlist";
	}
}
